package com.meida.module.bus.provider.handler;

import com.alibaba.fastjson.JSON;
import com.meida.common.base.entity.EntityMap;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.common.mybatis.interceptor.PageInterceptor;
import com.meida.common.mybatis.model.PageParams;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.module.admin.client.entity.BaseUser;
import com.meida.module.admin.provider.service.BaseUserService;
import com.meida.module.bus.client.entity.BusSubject;
import com.meida.module.user.client.entity.AppUser;
import com.meida.module.user.provider.service.AppUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 后台专业列表
 */
@Component
public class BusSubjectPageListHandler implements PageInterceptor<BusSubject> {

    @Autowired
    private AppUserService appUserService;
    @Autowired
    private BaseUserService baseUserService;

    @Override
    public void prepare(CriteriaQuery<BusSubject> cq, PageParams pageParams, EntityMap params) {
        cq.clear();
        Long parentId = params.getLong("parentId");
        cq.select(BusSubject.class, "subjectId", "subjectTitle", "parentId", "state", "amount", "userId", "userType", "remark", "createTime");
        cq.like(BusSubject.class, "subjectTitle");
        if (FlymeUtils.isEmpty(parentId)) {
            cq.eq(BusSubject.class, "parentId", 0);
        } else {
            cq.eq(BusSubject.class, "parentId", parentId);
        }
        cq.eq(BusSubject.class, "state");
    }

    @Override
    public void complete(CriteriaQuery<BusSubject> cq, List<EntityMap> result, EntityMap extra) {
        result.forEach(map -> {
            String userType = map.get("userType");
            map.put("createUser", "");
            if (FlymeUtils.isNotEmpty(userType)) {
                Long userId = map.getLong("userId");
                if (userType.equals(AppUser.class.getSimpleName())) {
                    if (FlymeUtils.isNotEmpty(userId)) {
                        AppUser appUser = appUserService.getById(userId);
                        if (FlymeUtils.isNotEmpty(appUser)) {
                            map.put("createUser", appUser.getNickName());
                        }
                    }
                }
                if (userType.equals(BaseUser.class.getSimpleName())) {
                    if (FlymeUtils.isNotEmpty(userId)) {
                        BaseUser baseUser = baseUserService.getById(userId);
                        if (FlymeUtils.isNotEmpty(baseUser)) {
                            map.put("createUser", baseUser.getUserName());
                        }
                    }
                }
            }
        });
    }


}
